#include "base.h"
#include <rtthread.h>
#include <stdlib.h>

static struct rt_mailbox mbox;

static rt_ubase_t mbox_buffer[8];

struct sensor_data {
    uint8_t temp;
    uint8_t hum;
};
static uint8_t mem_pool[8*(RT_ALIGN(sizeof(struct sensor_data), RT_ALIGN_SIZE) + sizeof(uint8_t *))];
static struct rt_mempool mpool;

static void sensor_read (struct sensor_data * data) {
    data->temp = 20 + rt_tick_get();
    data->hum = 50 + rt_tick_get();
}

void sender_entry (void * param) {    
    while (1) {
        struct sensor_data * data = (struct sensor_data *)rt_malloc(RT_WAITING_FOREVER);
        if (data != RT_NULL) {
            sensor_read(data);
            rt_mb_send_wait(&mbox, (rt_ubase_t)data, RT_WAITING_FOREVER);
        }
        
        rt_thread_mdelay(1000);
    }
}

void recv_entry (void * param) {
    while (1) {
        // recv
        struct sensor_data * data;
   
        rt_mb_recv(&mbox, (rt_ubase_t* )&data, RT_WAITING_FOREVER);
        
        //rt_kprintf("temp: %d, hum: %d\n", data->temp, data->hum);
        rt_free(data);
    }
}

static uint8_t heap1[10*1024];
struct  	rt_memheap mem_heap1;

static uint8_t heap2[10*1024];
struct  	rt_memheap mem_heap2;
int main(void) {
    hardware_init();
    
    rt_mb_init(&mbox, "mb", mbox_buffer, 8, RT_IPC_FLAG_FIFO);
    rt_memheap_init(&mem_heap1, "heap1", heap1, sizeof(heap1));
    rt_memheap_init(&mem_heap2, "heap12", heap2, sizeof(heap2));
    
    void * ptr1 = rt_malloc(5 * 1024);
    void * ptr2 = rt_malloc(5 * 1024);
    
    
    rt_thread_t t1 = rt_thread_create("t1", sender_entry, RT_NULL, 4096, 10, 10);
    rt_thread_startup(t1);
    rt_thread_t t2 = rt_thread_create("t2", recv_entry, RT_NULL, 4096, 10, 10);
    rt_thread_startup(t2);
    return 0;
}